package org.jaaksi.kottlindemo.home

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jaaksi.kottlindemo.R
import org.jetbrains.anko.toast
import timber.log.Timber

class SplashActivity : AppCompatActivity() {

    companion object {
        fun start(context: Activity, isBack: Boolean = true) {
            context.startActivity(
                Intent(
                    context,
                    SplashActivity::class.java
                ).apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    putExtra("isBack", isBack)
                })
            context.overridePendingTransition(0, 0)

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Timber.e("onCreate")
        setContentView(R.layout.activity_splash)
//        lifecycleScope.launch {
//            moveTaskToBack(false)
//            startActivity(Intent(this@SplashActivity, MainActivity::class.java))
//        }
        startActivity(Intent(this@SplashActivity, MainActivity::class.java))
        overridePendingTransition(0, 0)
        moveTaskToBack(false)
    }

    override fun onNewIntent(intent: Intent?) {
        Timber.e("onNewIntent")
        super.onNewIntent(intent)
        val isBack = intent?.getBooleanExtra("isBack", false) ?: false
        Timber.e("isBack = $isBack")
        lifecycleScope.launch {
            delay(1000)
            if (!isBack) {
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                overridePendingTransition(0, 0)
            } else {
                toast("从后台启动")
            }
            moveTaskToBack(false)

        }
    }

    override fun onRestart() {
        super.onRestart()
        Timber.e("onRestart")

    }

    override fun onBackPressed() {
//        moveTaskToBack(false)
    }
}